package com.example.hxds.common.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * @BelongsProject: hxds
 * @BelongsPackage: com.example.hxds.common.config
 * @Author: caohaoran
 * @CreateTime: 2025-10-18  17:23
 * @Description: 数据表的主键生成方式采用了雪花算法，所以主键字段都是bigint类型的，映射到Java中就是long类型。前端JS语言并不支持long类型，所以long类型数据都会出现自动截断。所以欧美要把返回给前端或者移动端的long类型数据转换成字符串格式。
 * @Version: 1.0
 */
@JsonComponent
public class JsonSerializerManage {

    @Bean
    //ObjectMapper:Jackson的核心类，负责JSON序列化和反序列化      Jackson2ObjectMapperBuilde:Spring提供的构造器，简化ObjectMapper配置
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        //createXmlMapper(false)：不创建xml映射器，只用于JSON
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        //忽略value为null时 key的输出
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        SimpleModule module = new SimpleModule();
        //长整型和浮点型在javaScript上面都会丢失精度，所以要转换成字符串类型
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        module.addSerializer(Double.class, ToStringSerializer.instance);
        module.addSerializer(Double.TYPE, ToStringSerializer.instance);
        module.addSerializer(Float.class, ToStringSerializer.instance);
        module.addSerializer(Float.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(module);
        return objectMapper;
    }
}
